package cn.rkylin.oms.system.shop.controller;

import java.io.Serializable;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.apollo.common.util.HttpUtil;
import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.export.IExport;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.dao.ShopDAOImpl;
import cn.rkylin.oms.system.shop.domain.ShopStor;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.service.IShopStorService;
import cn.rkylin.oms.system.shop.vo.ShopStorVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.service.IStorService;

/**
 * 店铺控制器
 *
 * @author wangxiaoyi
 * @version 1.0
 * @created 13-1月-2017 09:11:15
 */
@Controller
@RequestMapping("/shop")
public class ShopController extends ApolloController {
    private static final Log logger = LogFactory.getLog(ShopController.class);
    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShop"; // 分页语句Statement名称
    private static final String GOTO_SHOP_LIST = "/system/shop/shopList"; // 跳转到店铺列表页
    private static final String SHOP_VALIDATE_SUCCESS = "/ValidateSuccess.html";
    private static final String SHOP_VALIDATE_FAILED = "/ValidateFailed.html";

    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;

    /**
     * 项目服务层
     */
    @Autowired
    public ProjectManagerService projectManagerService;

    /**
     * 店铺仓库服务层
     */
    @Autowired
    private IShopStorService shopStorService;;
    

    /**
     * 仓库服务层
     */
    @Autowired
    private IStorService storService;

    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        setExportService((IExport) shopService);
    }

    /**
     * 跳转到店铺列表
     */
    @RequestMapping(value = "/gotoShopList")
    public String gotoShopList() {
        return GOTO_SHOP_LIST;
    }

    /**
     * 跳转到店铺列表
     *
     * @param quickSearch
     *            快速查询条件
     * @return 返回值JSON格式字符串
     * @Param start 第几页
     * @Param length 每页多少行
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/shopList", method = RequestMethod.GET)
    public Map<String, Object> getShopList(String quickSearch, String enable, String entId, String prjId,
            @RequestParam(required = false, defaultValue = "0") String popFlg, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 前台搜索条件，此处只有一个店铺名称
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");

            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            // 处理快速查询条件
            ShopVO param = new ShopVO();

            if (StringUtils.isNotEmpty(quickSearch)) {
                param.setSearchCondition(quickSearch);
            }

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId(projectId);
            }

            if (StringUtils.isNotEmpty(entId)) {
                param.setEntId(entId);
            }

            if ("1".equals(popFlg) && StringUtils.isEmpty(prjId) && StringUtils.isEmpty(entId)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put("recordsFiltered", 0);
                returnMap.put("recordsTotal", 0);
                returnMap.put(RETURN_DATA, new ArrayList<T>());
                return returnMap;
            }

            if (StringUtils.isNotEmpty(enable)) {
                List list = new ArrayList<String>(currentUser.getEnterpriseMap().keySet());
                param.setEnable(enable);
                if (list != null && list.size() > 0) {
                    param.setEnterpriseIdList(list);
                } else {
                    returnMap.put(JSON_RESULT, SUCCESS);
                    returnMap.put("recordsFiltered", 0);
                    returnMap.put("recordsTotal", 0);
                    returnMap.put(RETURN_DATA, new ArrayList<T>());
                    return returnMap;
                }
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShopDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 获取分页数据
            PageInfo<ShopVO> shopVOList = shopService.findByWhere(page, length, param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, shopVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, shopVOList.getTotal());
            returnMap.put(RETURN_DATA, shopVOList.getList());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取项目的平台店铺列表,不分页 即根据项目ID获取非子店铺列表
     * 
     * @param enable
     *            是否启用
     * @param entId
     *            企业ID
     * @param prjId
     *            项目ID
     * @return 返回值JSON格式字符串
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/unpagedShopList", method = RequestMethod.GET)
    public Map<String, Object> unpagedShopList(String enable, String entId, String prjId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {

            // 处理快速查询条件
            ShopVO param = new ShopVO();

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String currentProjectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId(currentProjectId);
            }

            if (StringUtils.isNotEmpty(entId)) {
                param.setEntId(entId);
            }

            /*
             * 默认查询启用的店铺
             */
            if (StringUtils.isNotEmpty(enable)) {
                param.setEnable(enable);
            } else {
                param.setEnable("y");
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            // 此处写死了，后期需根据情况放开
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShopDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 获取分页数据
            List<ShopVO> shopVOList = shopService.findByWhereAll(param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shopVOList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取项目的平台店铺列表,不分页 即根据项目ID获取非子店铺列表
     * 
     * @param enable
     *            是否启用
     * @param entId
     *            企业ID
     * @param prjId
     *            项目ID
     * @return 返回值JSON格式字符串
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/shopListIncloudingClosed", method = RequestMethod.GET)
    public Map<String, Object> shopListIncloudingClosed(String enable, String entId, String prjId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {

            // 处理快速查询条件
            ShopVO param = new ShopVO();

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String currentProjectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId(currentProjectId);
            }

            if (StringUtils.isNotEmpty(entId)) {
                param.setEntId(entId);
            }

            /*
             * 默认查询启用的店铺
             */
            param.setEnable("all");

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            // 此处写死了，后期需根据情况放开
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShopDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 获取分页数据
            List<ShopVO> shopVOList = shopService.findByWhereAll(param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shopVOList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取店铺明细信息
     *
     * @param shopId
     *            店铺id
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/shopDetail", method = RequestMethod.GET)
    public Map<String, Object> shopDetail(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO detailShop = shopService.getShopById(shopId);
            if (detailShop != null) {
                // // 获取店铺仓库数据
                // List<ShopStor> shopStorList =
                // shopStorService.getShopStorList(shopId);
                // // 设置返回结果内容
                // if (shopStorList != null && shopStorList.size() > 0) {
                // returnMap.put("shopWarehouseList", shopStorList);
                // }
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, detailShop);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该店铺不存在");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 获取子店铺列表
     *
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/childShopList", method = RequestMethod.GET)
    public Map<String, Object> childShopList(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO param = new ShopVO();
            param.setParentShop(shopId);
            PageInfo<ShopVO> parentShopList = shopService.findByWhere(1, Integer.MAX_VALUE, param);
            if (!parentShopList.getList().isEmpty()) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, parentShopList.getList());
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "没有子店铺");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 获取父店铺列表
     *
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/parentShopList", method = RequestMethod.GET)
    public Map<String, Object> parentShopList() throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO param = new ShopVO();
            param.setNeedSplitOrder(VALUE_YES);
            PageInfo<ShopVO> parentShopList = shopService.findByWhere(1, Integer.MAX_VALUE, param);
            if (!parentShopList.getList().isEmpty()) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, parentShopList.getList());
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "没有父店铺");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 获取指定项目店铺信息
     *
     * @param prjId
     *            项目ID
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getShopListByPrjId", method = RequestMethod.GET)
    public Map<String, Object> getShopListByPrjId(String prjId) throws Exception {
        prjId = URLDecoder.decode(prjId, "UTF-8");
        /// 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO param = new ShopVO();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId("00000000000000000000000000000000");
            }

            PageInfo<ShopVO> shopVOList = shopService.findByWhere(1, Integer.MAX_VALUE, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            // returnMap.put(RECORDS_FILTERED, shopVOList.getTotal());
            // returnMap.put(RECORDS_TOTAL, shopVOList.getTotal());
            returnMap.put(RETURN_DATA, shopVOList.getList());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取指定项目需要分单的店铺信息
     *
     * @param prjId
     *            项目ID
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getSplitShopList", method = RequestMethod.GET)
    public Map<String, Object> getSplitShopList(String prjId) throws Exception {
        prjId = URLDecoder.decode(prjId, "UTF-8");
        /// 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            ShopVO param = new ShopVO();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId(currentUser.getCurrentProject().getPrjId());
            }
            List<String> list = currentUser.getShopIdList();
            //param.setShopList(list);
            PageInfo<ShopVO> shopVOList = shopService.findSplitShop(1, Integer.MAX_VALUE, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shopVOList.getList());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取指定项目需要分单的店铺信息
     *
     * @param enable
     *            是否启用
     * @param entId
     *            企业ID
     * @param prjId
     *            项目ID
     * @return 返回值JSON格式字符串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getShopList", method = RequestMethod.GET)
    public Map<String, Object> getShopList(String enable, String entId, String prjId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {

            // 处理快速查询条件
            ShopVO param = new ShopVO();

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String currentProjectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isNotEmpty(prjId)) {
                param.setPrjId(prjId);
            } else {
                param.setPrjId(currentProjectId);
            }

            if (StringUtils.isNotEmpty(entId)) {
                param.setEntId(entId);
            }

            /*
             * 默认查询启用的店铺
             */
            if (StringUtils.isNotEmpty(enable)) {
                param.setEnable(enable);
            } else {
                param.setEnable("y");
            }

            // 获取分页数据
            List<ShopVO> shopVOList = shopService.findByWhereAll(param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shopVOList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 创建店铺
     *
     * @param shopVO
     *            前台值映射到ShopVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/addShop")
    @SystemControllerLog(module = "店铺管理", operation = "创建店铺", keyCode = "shopId")
    public Map<String, Object> addShop(@RequestBody ShopVO shopVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            if (isShopUnique(shopVO.getShopName(), shopVO.getShopType(), shopVO.getPrjId())) {
                shopVO.setShopId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                shopVO.setValidate(VALUE_YES);
                shopVO.setDeleted(VALUE_NO);
                shopVO.setCreateTime(new Date());
                shopVO.setModifyTime(new Date());
                // 店铺增加字段ent_id
                String entId = getUserEnterpriseId();
                shopVO.setEntId(entId);
                /*Object obj = redisTemplate.opsForValue().get("appKey:" + shopVO.getShopAccount());
                if (obj != null) {
                    shopVO.setApiUrl("http://gw.api.taobao.com/router/rest");
                    shopVO.setAppKey(shopVO.getShopAccount());
                    // 临时写死，前台好了再调
                    shopVO.setAppSecret(shopVO.getShopPassword());
                    Object strTopJSON = redisTemplate.opsForValue().get("appKey:" + shopVO.getShopAccount());
                    if (strTopJSON != null) {
                        JSONObject topJSON = JSONObject.parseObject((String) strTopJSON);
                        shopVO.setSessionKey(topJSON.getString("access_token"));
                        shopVO.setRefreshToken(topJSON.getString("refresh_token"));
                    }
                }*/
                // shopVO.setExpireTime(shopVO.getExpireTime());
                shopVO.setStartTime(new Date());
                shopService.insert(shopVO);
                returnMap.put(JSON_RESULT, SUCCESS);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该店铺名称与店铺类型已经存在");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopVO.getShopId());
        return returnMap;
    }

    /**
     * 获取当前登录用户的企业id
     * 
     * @return
     */
    private String getUserEnterpriseId() {
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
        String entId = (String) iterator.next();
        return entId;
    }

    /**
     * 验证店铺是否有效
     *
     * @param shopAccount
     *            APP KEY
     * @return true有效，false无效
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/isValidShop")
    public boolean isShopUnique(String shopAccount) throws Exception {
        shopAccount = URLDecoder.decode(shopAccount, "UTF-8");
        boolean result = false;

        Object appKey = redisTemplate.opsForValue().get("appKey:" + shopAccount);
        if (appKey == null) {
            result = false;
        } else {
            result = true;
        }

        return result;
    }

    /**
     * 判断店铺唯一性(店铺名称 + 店铺类型)
     *
     * @param shopName
     *            店铺名称
     * @param shopType
     *            店铺类型
     * @return true唯一，false不唯一
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/isShopUnique")
    public boolean isShopUnique(String shopName, String shopType, String prjId) throws Exception {
        shopName = URLDecoder.decode(shopName, "UTF-8");
        shopType = URLDecoder.decode(shopType, "UTF-8");
        prjId = URLDecoder.decode(prjId, "UTF-8");
        boolean result = false;
        ShopVO paramVO = new ShopVO();
        paramVO.setShopName(shopName);
        paramVO.setShopType(shopType);
        paramVO.setPrjId(prjId);
        paramVO.setDeleted("yn");
        PageInfo<ShopVO> shopList = shopService.findByWhere(1, 1, paramVO);
        if (shopList.getSize() > 0) {
            result = false;
        } else {
            result = true;
        }
        return result;
    }

    /**
     * 修改店铺
     *
     * @param shopVO
     *            前台值映射到ShopVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/updateShop")
    @SystemControllerLog(module = "店铺管理", operation = "修改店铺", keyCode = "shopId")
    public Map<String, Object> updateShop(@RequestBody ShopVO shopVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            shopService.update(shopVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopVO.getShopId());
        return returnMap;
    }

    /**
     * 修改店铺开关设置
     *
     * @param shopVO
     *            前台值映射到ShopVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/updateShopSwitchSet")
    @SystemControllerLog(module = "店铺管理", operation = "修改店铺开关设置", keyCode = "shopId")
    public Map<String, Object> updateShopSwitchSet(@RequestBody ShopVO shopVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        if (StringUtils.isEmpty(shopVO.getShopId())) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "未取得到店铺ID，请重试！");
        } else {
            try {
                shopService.update(shopVO);
                returnMap.put(JSON_RESULT, SUCCESS);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, ex.getMessage());
            }
        }
        returnMap.put("shopId", shopVO.getShopId());
        return returnMap;
    }

    /**
     * 删除店铺
     *
     * @param shopId
     *            店铺ID
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/deleteShop", method = RequestMethod.POST)
    @SystemControllerLog(module = "店铺管理", operation = "删除店铺", keyCode = "shopId")
    public Map<String, Object> deleteShop(String shopId) throws Exception {
        Map<String, Object> returnMap = new JSONObject();
        try {
            ShopVO paramVO = new ShopVO();
            paramVO.setShopId(shopId);
            PageInfo<ShopVO> shopList = shopService.findByWhere(1, 1, paramVO);
            if (shopList.getSize() > 0) {
                ShopVO updateShop = shopList.getList().get(0);
                updateShop.setDeleted(VALUE_YES);
                shopService.update(updateShop);
                returnMap.put(JSON_RESULT, SUCCESS);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "店铺不存在，请刷新后重试。");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }
    
    /**
     * 创建任务
     */
    @ResponseBody
    @RequestMapping(value = { "/initShop/{shopid}" })
    public Map<String, String> initShop(@PathVariable String shopid) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		try {
			shopService.initShop(shopid);
			map.put("result", "true");
		} catch (Exception e) {
			map.put("result", "false");
			map.put("msg", e.getMessage());
		}

		return map;
    }

    /**
     * 启用店铺 店铺过期时间必须大于现在，且店铺对应项目不能是停止状态
     *
     * @param shopId
     *            店铺ID
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/setEnable", method = RequestMethod.POST)
    @SystemControllerLog(module = "店铺管理", operation = "启用店铺", keyCode = "shopId")
    public Map<String, Object> setEnable(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO shopVO = new ShopVO();
            shopVO.setShopId(shopId);
            PageInfo<ShopVO> shopList = shopService.findByWhere(1, 1, shopVO);
            if (shopList.getSize() > 0) {
                ShopVO updateShop = shopList.getList().get(0);

                // 如果项目已经停用了，则店铺不能启用。
                ProjectVO prjVO = new ProjectVO();
                prjVO.setPrjId(updateShop.getPrjId());
                PageInfo<ProjectVO> projectVOList = projectManagerService.findByWhere(1, 1, prjVO);

                if (projectVOList.getSize() > 0) { // 店铺对应的项目存在
                    if (projectVOList.getList().get(0).getEnable().equalsIgnoreCase("y")) {
                        // 启用店铺，必须设置过期时间，且过期时间要大于当前时间
                        Long now = (new Date()).getTime();
                        if (updateShop.getExpireTime() != null && updateShop.getExpireTime().getTime() >= now) {
                            updateShop.setEnable(VALUE_YES);
                            shopService.update(updateShop);
                            returnMap.put(JSON_RESULT, SUCCESS);
                        } else {
                            returnMap.put(JSON_RESULT, FAILED);
                            returnMap.put(JSON_MSG, "必须设置过期时间，且过期时间要大于当前时间。");
                        }
                    } else { // 店铺对应的项目已经停用
                        returnMap.put(JSON_RESULT, FAILED);
                        returnMap.put(JSON_MSG, "不能启用店铺，因项目处于“停用”状态。");
                    }
                } else { // 店铺对应的项目不存在
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "店铺对应的项目不存在。");
                }

            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "店铺不存在，请刷新后重试。");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * 禁用店铺
     *
     * @param shopId
     *            店铺ID
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/setDisable", method = RequestMethod.POST)
    @SystemControllerLog(module = "店铺管理", operation = "禁用店铺", keyCode = "shopId")
    public Map<String, Object> setDisable(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShopVO shopVO = new ShopVO();
            shopVO.setShopId(shopId);
            PageInfo<ShopVO> shopList = shopService.findByWhere(1, 1, shopVO);
            if (shopList.getSize() > 0) {
                ShopVO updateShop = shopList.getList().get(0);
                updateShop.setEnable(VALUE_NO);
                shopService.update(updateShop);
                returnMap.put(JSON_RESULT, SUCCESS);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "店铺不存在，请刷新后重试。");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("shopId", shopId);
        return returnMap;
    }

    /**
     * 电商平台店铺验证成功后的回调
     *
     * @param shopId
     *            店铺ID
     * @param appKey
     *            淘宝回调的appKey
     * @param appSecret
     *            淘宝回调的appSecret
     * @param code
     *            淘宝回调的code
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/validated")
    public String validated(String shopId, String appKey, String appSecret, String code, String error_description) throws Exception {
        JSONObject returnMap = new JSONObject();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (StringUtils.isBlank(appKey) || StringUtils.isBlank(appSecret) || StringUtils.isBlank(code)) {
            returnMap.put(JSON_RESULT, FAILED);
            String errorMessage = "";
            if (StringUtils.isNotBlank(error_description)) {
                errorMessage = error_description;
            } else {
                errorMessage = "验证返回值错误：appKey，appSecret，code";
            }
            returnMap.put(JSON_MSG, errorMessage);
            return returnMap.toJSONString();
        }

        // 淘宝店铺token更新(目前只有一种，其它方式不确定，以后对接其它平台再重构到具体的模式)
        // TODO 扩展其它平台
        // 缓存淘宝access token
        String taobaoReturn = cacheTaoBaoAccessToken(appKey, appSecret, code);
        if (StringUtils.isNotBlank(taobaoReturn)) { // 有错误返回
            response.sendRedirect(SHOP_VALIDATE_FAILED);
            return "";
        } else {
            response.sendRedirect(SHOP_VALIDATE_SUCCESS);
            return "";
        }
    }

    /**
     * 缓存淘宝的店铺验证结果(access_token访问淘宝用的token，这个token的有效时长，在淘宝商家后台设置)
     * 
     * @param appKey
     *            淘宝回调的appKey
     * @param appSecret
     *            淘宝回调的appSecret
     * @param code
     *            淘宝回调的code
     */
    private String cacheTaoBaoAccessToken(String appKey, String appSecret, String code) {
        String returnValue = null;
        String url = "https://oauth.taobao.com/token";
        StringBuffer props = new StringBuffer();
        props.append("grant_type=authorization_code");
        props.append("&code=" + code);
        props.append("&client_id=" + appKey);
        props.append("&client_secret=" + appSecret);
        props.append("&redirect_uri=http://ecs3.ruixuesoft.com:30001"); // oms项目地址
        props.append("&view=" + "web");
        try {
            String topPostResult = HttpUtil.sendByPost(url, props.toString(), "");// "{\"taobao_user_nick\":\"liming1019\",\"re_expires_in\":23035102,\"expires_in\":23035102,\"expire_time\":1520028000000,\"r1_expires_in\":23035102,\"w2_valid\":1496994697366,\"w2_expires_in\":1800,\"taobao_user_id\":\"50081830\",\"w1_expires_in\":23035102,\"r1_valid\":1520028000000,\"r2_valid\":1497252097366,\"w1_valid\":1520028000000,\"r2_expires_in\":259200,\"token_type\":\"Bearer\",\"refresh_token\":\"6200f13c44773e1eedf0ceg0edfee41f2295f2ca5730ca450081830\",\"refresh_token_valid_time\":1520028000000,\"access_token\":\"6201513b52ccdf0abbeefhj5a9d9b40792997b5c64e063b50081830\"}";//
            if (StringUtils.isNotBlank(topPostResult)) {
                // logger.debug(">>>>>> 这里是 淘宝获取access token的结果：" +
                // topPostResult);
                if (topPostResult != null) {
                    redisTemplate.opsForValue().set("appKey:" + appKey, topPostResult);
                    redisTemplate.expire("appKey:" + appKey, 24, TimeUnit.HOURS);
                }
            } else {
                returnValue = "淘宝验证错误";
            }
        } catch (Exception ex) {
            returnValue = ex.getMessage();
            logger.error(ex.getMessage(), ex);
        }
        return returnValue;
    }

    /**
     * 添加店铺仓库
     *
     * @param shopStor
     *            前台值映射到ShopStor
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/saveSelectedWarehouse")
    @SystemControllerLog(module = "店铺管理", operation = "添加店铺仓库", keyCode = "shopId")
    public Map<String, Object> saveSelectedWarehouse(@RequestBody ShopStorVO shopStor) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser curUser = WebContextFactory.getWebContext().getCurrentUser();

        if (curUser == null || StringUtils.isBlank(shopStor.getShopId()) || StringUtils.isBlank(shopStor.getShopName())
                || StringUtils.isBlank(shopStor.getStorId()) || StringUtils.isBlank(shopStor.getStorName())
                || StringUtils.isBlank(shopStor.getIsDefault()) || StringUtils.isBlank(shopStor.getIsSyncStock())) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "参数错误");
        } else {
            try {
                // 新建的店铺仓库是否已经存在
                if (StringUtil.isBlank(shopStor.getShopStorId())) { // 新建
                    ShopStorVO isShopStorExist = new ShopStorVO();
                    isShopStorExist.setShopId(shopStor.getShopId());
                    isShopStorExist.setStorId(shopStor.getStorId());
                    List<ShopStorVO> tempList = shopStorService.getShopStorByCondition(isShopStorExist);
                    if (tempList != null && tempList.size() > 0) {
                        returnMap.put(JSON_MSG, "店铺已经存在此仓库，不能继续添加");
                        returnMap.put(JSON_RESULT, FAILED);
                        return returnMap;
                    }
                }

                ProjectVO currProject = curUser.getCurrentProject();

                // 从店铺上获取项目信息
                ShopVO shop = shopService.getShopById(shopStor.getShopId());
                shopStor.setPrjId(shop.getPrjId());
                shopStor.setPrjName(shop.getPrjName());
                // 从店铺上获取项目信息

                shopStor.setEntId(currProject.getEntId());
                shopStor.setDeleted(YesNoConst.NO);
                if ("true".equalsIgnoreCase(shopStor.getIsDefault())) {
                    shopStor.setIsDefault(YesNoConst.YES);
                } else {
                    shopStor.setIsDefault(YesNoConst.NO);
                }
                if ("true".equalsIgnoreCase(shopStor.getIsSyncStock())) {
                    shopStor.setIsSyncStock(YesNoConst.YES);
                } else {
                    shopStor.setIsSyncStock(YesNoConst.NO);
                }
                
                // 2018年7月20日 前台仓库名称可能随时变化显示，这里直接重新取一下
                if (StringUtils.isNotBlank(shopStor.getStorId())) {
                    Stor storDetail = storService.selectStorDetail(shopStor.getStorId());
                    if (storDetail != null) {
                        shopStor.setStorName(storDetail.getStorName());
                    }
                }

                // 如果是更新默认仓库，则需要先去掉其它默认仓库
                if (shopStor.getIsDefault().equalsIgnoreCase(YesNoConst.YES)) {
                    ShopStorVO updateDefaultParam = new ShopStorVO();
                    updateDefaultParam.setIsDefault(YesNoConst.NO);
                    updateDefaultParam.setWhereShopId(shopStor.getShopId());
                    shopStorService.updateShopStor(updateDefaultParam);
                }

                if (StringUtil.isBlank(shopStor.getShopStorId())) { // 新建
                    shopStor.setShopStorId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    shopStorService.insertShopStor(shopStor);
                    returnMap.put(JSON_MSG, "添加店铺仓库成功");
                } else { // 修改
                    // 根据shopStorId查询ShopStorVO，用于判断修改整个仓库，还是部分仓库信息
                    ShopStorVO isShopStorSelf = new ShopStorVO();
                    isShopStorSelf.setShopStorId(shopStor.getShopStorId());
                    List<ShopStorVO> tempList = shopStorService.getShopStorByCondition(isShopStorSelf);

                    // 获取店铺仓库数据
                    List<ShopStorVO> shopStorList = shopStorService.getShopStorList(shopStor.getShopId());
                    for (int i = 0; i < shopStorList.size(); i++) {
                        // 仓库存在于当前店铺中且不是所修改的店铺本身
                        if (shopStor.getStorId().equals(shopStorList.get(i).getStorId())
                                && !shopStor.getStorId().equals(tempList.get(0).getStorId())) {
                            returnMap.put(JSON_MSG, "修改后的目标仓库已存在");
                            returnMap.put(JSON_RESULT, FAILED);
                            return returnMap;
                        }
                    }
                    shopStorService.updateShopStor(shopStor);
                    returnMap.put(JSON_MSG, "修改店铺仓库成功");
                }
                returnMap.put(JSON_RESULT, SUCCESS);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, ex.getMessage());
            }
        }
        returnMap.put("shopId", shopStor.getShopId());
        return returnMap;
    }
    
    /**
     * 保存默认退货仓库
     *
     * @param shopStorIds
     *            店铺仓库列表
     * @param storId
     *            默认退货仓库Id
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/saveDefaultReturnWarehouse")
    @SystemControllerLog(module = "店铺管理", operation = "更新店铺默认退货仓库", keyCode = "shopStorId")
    public Map<String, Object> saveDefaultReturnWarehouse(@RequestParam String shopStorIds,@RequestParam String storId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser curUser = WebContextFactory.getWebContext().getCurrentUser();
        
        if (StringUtils.isEmpty(shopStorIds)) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "参数错误");
        } else {
            String[] shopStorIdArray = shopStorIds.split(",");
            try {
                for (String shopStorId : shopStorIdArray) {
                    ShopStorVO shopStor = new ShopStorVO();
                    shopStor.setShopStorId(shopStorId);
                    shopStor.setReturnStorId(storId);
                    // 更新店铺仓库的默认退货仓库
                    shopStorService.updateShopStor(shopStor);
                    returnMap.put(JSON_RESULT, SUCCESS);
                    returnMap.put(JSON_MSG,"操作成功");
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "操作失败，请联系系统管理员");
            }
        }
        return returnMap;
    }
    
    /**
     * getDefaultReturnWarehouse:根据店铺仓库获取默认退货仓库. <br/>
     *
     * @author zhanghao
     * @param shopId
     * @param storId
     * @param prjId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getDefaultWarehouseByShopStor")
    @SystemControllerLog(module = "店铺管理", operation = "获取店铺仓库的默认退货仓库", keyCode = "storId")
    public Map<String, Object> getDefaultReturnWarehouse(@RequestParam String shopId,@RequestParam String storId,@RequestParam String prjId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        
        if (StringUtils.isEmpty(shopId)||StringUtils.isEmpty(storId)||StringUtils.isEmpty(prjId)) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "参数错误");
        } else {
            ShopStorVO param = new ShopStorVO();
            param.setShopId(shopId);
            param.setStorId(storId);
            try {
                List<ShopStorVO> resultList = shopStorService.getShopStorByCondition(param);
                if(resultList.size()>0) {
                    returnMap.put(JSON_RESULT,SUCCESS);
                    returnMap.put(RETURN_DATA, resultList.get(0).getReturnStorId());
                }else {
                    returnMap.put(JSON_RESULT, SUCCESS);
                    returnMap.put(RETURN_DATA,StringUtils.EMPTY);
                }
            }catch (Exception e) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG,"未获取到退货仓库，请联系系统管理员");
            }
        }
        return returnMap;
    }

    /**
     * 获取店铺下的所有仓库
     * 
     * @param shopId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getShopWarehouseList", method = RequestMethod.GET)
    public Map<String, Object> getShopWarehouseList(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            if (StringUtils.isNotBlank(shopId)) {
                // 获取店铺仓库数据
                List<ShopStorVO> shopStorList = shopStorService.getShopStorList(shopId);
                // 设置返回结果内容
                if (shopStorList != null && shopStorList.size() > 0) {
                    returnMap.put("data", shopStorList);
                }
                returnMap.put(RECORDS_TOTAL, shopStorList.size());
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, shopStorList);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(RETURN_DATA, "");
                returnMap.put(JSON_MSG, "未指定店铺");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 获取店铺下的所有仓库
     * 
     * @param shopId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/deleteShopWarehouse", method = RequestMethod.GET)
    @SystemControllerLog(module = "店铺管理", operation = "删除店铺仓库", keyCode = "shopStorId")
    public Map<String, Object> deleteShopStor(String shopStorId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        if (StringUtils.isBlank(shopStorId)) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "参数错误");
        } else {
            try {
                shopStorService.deleteShopStor(shopStorId);
                returnMap.put(JSON_RESULT, SUCCESS);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, ex.getMessage());
            }
        }
        returnMap.put("shopStorId", shopStorId);
        return returnMap;
    }

    /**
     * 获取店铺下的所有仓库
     * 
     * @param shopId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/changeShopStorSyncStatus", method = RequestMethod.GET)
    @SystemControllerLog(module = "店铺管理", operation = "设置店铺库存同步仓库", keyCode = "shopStorId")
    public Map<String, Object> deleteShopStor(String shopStorId, Integer operation) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        if (StringUtils.isBlank(shopStorId)) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "参数错误");
        } else {
            try {
                ShopStorVO updateSyncParam = new ShopStorVO();
                updateSyncParam.setShopStorId(shopStorId);
                if (operation == 0) {
                    updateSyncParam.setIsSyncStock(YesNoConst.YES);
                } else {
                    updateSyncParam.setIsSyncStock(YesNoConst.NO);
                }
                shopStorService.updateShopStor(updateSyncParam);
                returnMap.put(JSON_RESULT, SUCCESS);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, ex.getMessage());
            }
        }
        returnMap.put("shopStorId", shopStorId);
        return returnMap;
    }
}